package com.ar.mylibrary;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;

import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

import android.widget.Toast;

import androidx.annotation.NonNull;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.model.LatLng;
import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


public class MainActivity extends UnityPlayerActivity {

    public float[] SensorOrientation=new float[3];
    private SensorManager sensorManager;
    private MySensorEventListener mySensorEventListener;

    LocationManager locationManager ;
    WifiUtil _WifiUtil;
    private BluetoothAdapter bluetoothAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mySensorEventListener= new MySensorEventListener();
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        RunSensorListener();
        //Toast.makeText(MainActivity.this, "sensorManager", Toast.LENGTH_LONG);
        _WifiUtil = new WifiUtil(this);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(!hasBasePhoneAuth())
        {
            InitNavi();
        }
        else
        {
            InitLocationOption();
        }

    }
    private  float lastX;
    private final class MySensorEventListener implements SensorEventListener {

        @Override
        //可以得到传感器实时测量出来的变化值
        public void onSensorChanged(SensorEvent event) {
            //方向传感器
            if(event.sensor.getType()== Sensor.TYPE_ORIENTATION){
                //x表示手机指向的方位，0表示北,90表示东，180表示南，270表示西
                float x=event.values[SensorManager.DATA_X];
                if(Math.abs(x-lastX)>1.0)
                {
                    //Toast.makeText(MainActivity.this, String.format("%1$5.2f", x), Toast.LENGTH_LONG);
                    UnityPlayer.UnitySendMessage("AndoridInteractive", "ReceiveDirectionX", String.format("%1$5.2f", x));
                }
                lastX=x;


               // SensorOrientation[1] = event.values[SensorManager.DATA_Y];
                //SensorOrientation[2] = event.values[SensorManager.DATA_Z];
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // TODO Auto-generated method stub
        }
    }


    private Toast msg;
    public  void ShowMessage(String message,int  type)
    {
        //短
        if(type==0)
        {
            msg = Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT);
        }
        else if(type==1)
        {
            msg = Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG);
        }
        else
        {
            msg = Toast.makeText(MainActivity.this, message, type);
        }
        msg.show();

    }

    public  void  HideMessage()
    {
        if(msg!=null)
        {
            msg.cancel();
        }
    }

//申请权限
    private static final String[] authBaseArr = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
    private boolean hasBasePhoneAuth() {
        PackageManager pm = getPackageManager();
        for (String auth : authBaseArr) {
            if (pm.checkPermission(auth, getPackageName()) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
    private static final int authBaseRequestCode = 1;
    private void InitNavi() {
        // 申请权限
        if (android.os.Build.VERSION.SDK_INT >= 23) {
            this.requestPermissions(authBaseArr, authBaseRequestCode);

        }
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case authBaseRequestCode:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {

                    //进行了授权
                    InitLocationOption();

                } else {
                    //禁止授
                    UnityPlayer.UnitySendMessage("AndoridInteractive", "ErrorHandle", "");
                }
                break;
            default:
                break;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    protected void RunSensorListener(){

        Sensor sensor_orientation=sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        sensorManager.registerListener(mySensorEventListener,sensor_orientation, SensorManager.SENSOR_DELAY_UI);
    }

    protected void StopSensorListener()
    {
        sensorManager.unregisterListener(mySensorEventListener);
    }

    private void InitLocationOption() {
        LocationClient locationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类实例并配置定位参数
        LocationClientOption locationOption = new LocationClientOption();
        MyLocationListener myLocationListener = new MyLocationListener();
        //注册监听函数
        locationClient.registerLocationListener(myLocationListener);
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        locationOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认gcj02，设置返回的定位结果坐标系，如果配合百度地图使用，建议设置为bd09ll;
       // locationOption.setCoorType("bd09ll");
        locationOption.setCoorType("gcj02");

        //可选，默认0，即仅定位一次，设置发起连续定位请求的间隔需要大于等于1000ms才是有效的
        locationOption.setScanSpan(1000);
        //可选，设置是否需要地址信息，默认不需要
        locationOption.setIsNeedAddress(false);
        //可选，设置是否需要地址描述
        locationOption.setIsNeedLocationDescribe(false);
        //可选，设置是否需要设备方向结果
        locationOption.setNeedDeviceDirect(false);
        //可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        locationOption.setLocationNotify(true);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        locationOption.setIgnoreKillProcess(false);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        locationOption.setIsNeedLocationDescribe(false);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        locationOption.setIsNeedLocationPoiList(false);
        //可选，默认false，设置是否收集CRASH信息，默认收集
        locationOption.SetIgnoreCacheException(false);
        //可选，默认false，设置是否开启Gps定位
        locationOption.setOpenGps(true);
        //可选，默认false，设置定位时是否需要海拔信息，默认不需要，除基础定位版本都可用
        locationOption.setIsNeedAltitude(false);
        //设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者，该模式下开发者无需再关心定位间隔是多少，定位SDK本身发现位置变化就会及时回调给开发者
        locationOption.setOpenAutoNotifyMode();
        //设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者
        locationOption.setOpenAutoNotifyMode(1000,1, LocationClientOption.LOC_SENSITIVITY_HIGHT);
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        locationClient.setLocOption(locationOption);
        //开始定位
        locationClient.start();


        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    Activity#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for Activity#requestPermissions for more details.
            return;
        }
        locationManager.addGpsStatusListener(statusListener);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locationListener);

    }

    LocationListener locationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {

        }

        @Override
        public void onStatusChanged(String provider, int status,
                                    Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }

    };
    private final GpsStatus.Listener statusListener = new GpsStatus.Listener() {
        public void onGpsStatusChanged(int event) { // GPS状态变化时的回调，如卫星数
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                return;
            }
            GpsStatus status = locationManager.getGpsStatus(null); // 取当前状态
            updateGpsStatus(event, status);
        }
    };

    private int count = 0;
    private ArrayList<GpsSatellite> numSatelliteList =new ArrayList<GpsSatellite> ();
    private void updateGpsStatus(int event, GpsStatus status) {
        if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS) {
            int maxSatellites = status.getMaxSatellites();
            Iterator<GpsSatellite> it = status.getSatellites().iterator();
            numSatelliteList.clear();
             count = 0;
            while (it.hasNext() && count <= maxSatellites) {
                GpsSatellite s = it.next();
                if(s.getSnr()!=0)//只有信躁比不为0的时候才算搜到了星
                {
                    numSatelliteList.add(s);
                    count++;
                }
            }


        }
    }

    public  String GetGPSCount()
    {
        return count+"";
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {

              //获取经度信息
           // float radius = location.getRadius();    //获取定位精度，默认值为0.0f
           // String coorType = location.getCoorType();
            //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准
            //int errorCode = location.getLocType();
            //获取网络定位
//            if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
//
//            }
//            //GPS定位
//            else if(location.getLocType() == BDLocation.TypeGpsLocation )
//            {
                double latitude = location.getLatitude();    //获取纬度信息
                double longitude = location.getLongitude();
                UnityPlayer.UnitySendMessage("AndoridInteractive", "ReceiveLocation", latitude+","+longitude);
           // }

        }
    }

    ///判断是否开启了定位开关
    //type 为0 gps 开关 ，1 为wifi开关
    public  String GetGPSSetting() {

           boolean result = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            if (result) {
                //UnityPlayer.UnitySendMessage("SensorOrientation", "SettingLocateResult", "0");
                return "0";
            } else {
                //UnityPlayer.UnitySendMessage("SensorOrientation", "SettingLocateResult", "1");
                return "1";
            }

    }
//判断蓝牙开关开启
    public String GetBlueToothState() {
        // 获取蓝牙状态
        boolean result = bluetoothAdapter.isEnabled();
        if(result)
        {

            return "0";
        }
        else

        {
            return "1";
        }

    }

}
